import { Suspense } from "react";
import { BookOpenTextIcon } from "lucide-react";

import { createGitHubClient } from "@repo/api/github";
import {
  getProjectRepositoryURL,
  type ProjectDetails,
} from "@repo/db/projects";

import { ErrorBoundary } from "@/app/error-handling";
import { ExternalLinkIcon } from "@/components/core";
import { buttonVariants } from "@/components/ui/button";
import { Card, CardHeader } from "@/components/ui/card";
import { cn } from "@/lib/utils";

export async function ReadmeCard({ project }: { project: ProjectDetails }) {
  return (
    <Card>
      <CardHeader className="border-b">
        <div className="flex space-x-2">
          <BookOpenTextIcon className="size-6" />
          <div>README</div>
        </div>
      </CardHeader>
      <div className="markdown-body p-4">
        <ErrorBoundary fallback={<>Unable to load the project README</>}>
          <Suspense fallback={<>Loading README.md</>}>
            <ReadmeContent project={project} />
          </Suspense>
        </ErrorBoundary>
      </div>
      <div className="border-t p-4">
        <a
          href={getProjectRepositoryURL(project)}
          className={cn(
            buttonVariants({ variant: "link" }),
            "w-full text-md text-secondary-foreground",
          )}
        >
          View {project.name} on GitHub
          <ExternalLinkIcon size={16} />
        </a>
      </div>
    </Card>
  );
}

async function ReadmeContent({ project }: { project: ProjectDetails }) {
  const gitHubClient = createGitHubClient();
  const { full_name, default_branch } = project.repo;
  const html = await gitHubClient.fetchRepoReadMeAsHtml(full_name, {
    branch: default_branch || "main",
    path: project.packagePath, // Support monorepo packages with specific directories
  });
  // biome-ignore lint/security/noDangerouslySetInnerHtml: HTML is generated by one of our functions
  return <div dangerouslySetInnerHTML={{ __html: html }} />;
}
